<template>
	<div class="feed-container">
		<nav-bar title="消息提醒" :custom-back="true" @on-back="handleBack" />
		<!-- 公告内容 -->
		<div class="section">
			<div class="title">{{ detailInfo.noticeInfo.title }}</div>
			<div class="html">{{ detailInfo.noticeInfo.content }}</div>
			<van-button v-if="showSignButton" type="primary" block @click="addAnnunciate">
				签收
			</van-button>
		</div>

		<!-- 发布信息 -->
		<template v-if="detailType != 1 && detailInfo.noticeInfo">
			<div class="section info-section">
				<van-cell-group>
					<van-cell title="发布人" :value="detailInfo.noticeInfo.createUser" />
					<van-cell title="需审批" :value="detailInfo.noticeInfo.isNeedApprove == 1 ? '是' : '否'" />
					<van-cell title="需签收" :value="detailInfo.noticeInfo.isNeedSign == 1 ? '是' : '否'" />
				</van-cell-group>
			</div>

			<!-- 状态统计 -->
			<div class="status-section">
				<div class="section-title">
					<span class="title-bar"></span>
					{{ detailInfo.noticeInfo.isNeedSign == 1 ? '签收' : '阅读' }}状态
				</div>

				<van-cell-group>
					<van-cell :title="detailInfo.noticeInfo.isNeedSign == 1 ? '已签' : '已读'"
						:value="detailInfo.noticeInfo.isNeedSign == 1 ? detailInfo.yesSignCount : detailInfo.yesReadCount"
						is-link @click="goReadLog('1')" />
					<van-cell :title="detailInfo.noticeInfo.isNeedSign == 1 ? '未签' : '未读'"
						:value="detailInfo.noticeInfo.isNeedSign == 1 ? detailInfo.noSignCount : detailInfo.noReadCount"
						is-link @click="goReadLog('2')" />
				</van-cell-group>
			</div>

			<!-- 附件列表 -->
			<template v-if="detailInfo.noticeFileList?.length">
				<div class="section-title">
					<span class="title-bar"></span>
					附件
				</div>

				<div class="file-list">
					<div v-for="(item, index) in detailInfo.noticeFileList" :key="index" class="file-item"
						@click="openFile(item.accessPath)">
						<van-image :src="getFilePath(item)" />
						<span class="file-name">{{ item.fileName }}</span>
					</div>
				</div>
			</template>

			<!-- 审批流程 -->
			<process v-if="detailInfo.noticeInfo.isNeedApprove == 1" :detail="detailInfo" />

			<!-- 操作按钮 -->
			<div class="action-buttons">
				<!-- 根据不同状态显示不同按钮 -->
				<template v-if="curId == '1'">
					<van-button v-if="showSignButton" type="primary" block @click="handSign">
						签收
					</van-button>
				</template>

				<template v-else>
					<!-- 审批操作 -->
					<template v-if="showApproveButtons">
						<van-field v-model="result" type="textarea" placeholder="审批意见" maxlength="200"
							show-word-limit />

						<div class="approve-buttons">
							<van-button type="danger" :loading="loading" @click="handConsent('3')">
								驳回
							</van-button>
							<van-button type="primary" :loading="loading" @click="handConsent('2')">
								同意
							</van-button>
						</div>
					</template>

					<!-- 发布者操作 -->
					<template v-else>
						<van-button v-if="showRecallButton" type="warning" block @click="canclePosted">
							撤回
						</van-button>

						<div v-if="showRetryButtons" class="retry-buttons">
							<van-button type="warning" @click="handRetry">
								重发
							</van-button>
							<van-button type="danger" @click="handDelete">
								删除
							</van-button>
						</div>
					</template>
				</template>
			</div>
		</template>

		<!-- 审批人选择弹窗 -->
		<van-popup v-model="showApproverTree" position="bottom" :style="{ height: '50%' }">
			<tree-select ref="treeApprover" :data="dataTree" :is-open-all="true" :is-choice="true"
				@select="handleApproverClick" />
		</van-popup>

		<!-- 确认弹窗 -->
		<van-dialog v-model="showDialog" />
	</div>
</template>

<script module="util" lang="wxs" src="@/utils/util.wxs"></script>
<script>
	import NavBar from '@/components/NavBar'
	import {
		saveNotice,
		listNotice,
		getNoticeDetail,
		getDeptUserTree,
		doUploadBatchFile,
		doReadNotice,
		doSignNotice,
		doRecallNotice,
		deleteNotice,
		doHandle
	} from "@/api/annunciateDetail.js"
	import tree from '@/components/tree/index';
	import process from '@/components/process/index';
	import {
		Toast,
		Dialog
	} from 'vant'

	export default {
		name: 'AnnounceDetail',

		components: {
			process,
			process,
			NavBar
		},

		data() {
			return {
				approver: [],
				showApproverTree: false,
				dataTree: [],
				list: [],
				detailType: null,
				detailId: 0,
				taskId: 0,
				detailInfo: {
					noticeInfo: {
						title: '',
						content: '',
						approveStatus: 0,
						isNeedSign: 0,
						createUser: '',
						isNeedApprove: 0,
						isRecall: 0
					},
					yesSignCount: '',
					yesReadCount: '',
					noSignCount: '',
					noReadCount: '',
					noticeFileList: []
				},
				result: '',
				curId: undefined, // 1:我接收 2:我发布
				isRec: 0, // 0:未签收 1:已签收
				entrance: '', // 入口 1:申请列表 2:审批列表
				handleState: '', // 1:待审批 2:已审批
				isApprove: false, // 是否已审批
				loading: false,
				showDialog: false,
				user: []
			}
		},

		computed: {
			// 是否显示签收按钮
			showSignButton() {
				const {
					noticeInfo
				} = this.detailInfo
				return noticeInfo.approveStatus == 1 &&
					this.detailType == 1 &&
					noticeInfo.isNeedSign == 1
			},

			// 是否显示审批按钮
			showApproveButtons() {
				return this.taskId &&
					this.detailInfo.noticeInfo.approveStatus == 1 &&
					this.detailInfo.noticeInfo.isNeedApprove == 1 &&
					!this.isApprove &&
					this.handleState == 1
			},

			// 是否显示撤回按钮  
			showRecallButton() {
				const {
					noticeInfo
				} = this.detailInfo
				return this.entrance != 2 &&
					noticeInfo.isRecall == 0 &&
					noticeInfo.approveStatus == 1
			},

			// 是否显示重发/删除按钮
			showRetryButtons() {
				const {
					noticeInfo
				} = this.detailInfo
				return this.entrance != 2 &&
					(noticeInfo.isRecall == 1 || noticeInfo.approveStatus == 2)
			}
		},

		created() {
			this.user = JSON.parse(localStorage.getItem('user'))
			// 获取路由参数
			const {
				id,
				taskId,
				curId,
				isRec,
				entrance,
				state
			} = this.$route.query
			this.detailId = id || 0
			this.taskId = taskId || 0
			this.curId = curId
			this.isRec = isRec || 0
			this.entrance = entrance || ''
			this.handleState = state || ''

			this.getDeptUserTree()
		},

		methods: {
			handleBack() {
				this.$router.push('/annunciate')
			},
			// 获取部门用户树
			getDeptUserTree() {
				try {
					getDeptUserTree({
							openSessionId: this.user.openSessionId,
						})
						.then(res => {

							if (res.code == 200) {
								this.dataTree = res.data
								if (this.detailId) {
									this.loadDetailData()
								}
							}
						})

				} catch (err) {
					console.log(err)
					Toast.fail('获取部门用户树失败')
				}
			},


			// 加载详情数据
			async loadDetailData() {
				try {

					getNoticeDetail({
							openSessionId: this.user.openSessionId,
							id: this.detailId
						})
						.then(res => {
							if (res.code === 200) {
								const data = res.data

								// 处理审批列表数据
								data.approvalList = data.approveList.map(item => ({
									...item,
									result: item.approveStatus === 2 ? 3 : item.approveStatus === 3 ?
										2 : item.approveStatus,
									name: item.approveUserName,
									roleName: item.approveDeptName,
									endTime: item.approvedTime || '',
									comment: item.avatar || item.approveAdvise
								}))

								// 判断是否已审批
								const isApprove = data.approvalList.some(x =>
									x.approveStatus == 1 && x.loginId == this.user.uLoginId
								)

								this.detailInfo = data
								this.detailType = data.noticeInfo.type
								this.isApprove = isApprove

								// 处理未读状态
								if (this.shouldAutoRead(data)) {
									this.doReadNotice(data.noticeInfo.id)
								}
							} else {
								Toast.fail(res.message)
							}
						})
				} catch (err) {
					Toast.fail(err)
				}
			},

			// 是否需要自动标记已读
			shouldAutoRead(data) {
				const userInfo = localStorage.getItem('userInfo')
				return data.noticeInfo.isNeedSign == 0 &&
					data.noticeInfo.isRec == 0 &&
					this.curId == 1 &&
					data.noReadList.some(x => x.userId == userInfo.id)
			},
			// 标记已读
			async doReadNotice(id) {
				try {
					doReadNotice({
							noticeId: id,
						})
						.then(res => {

							if (res.code == 200) {
								Toast.success(res.message)
							} else {
								Toast.error(res.message)
							}
						})

				} catch (err) {
					Toast.fail(error)
				}
			},

			// 签收
			async handSign() {
				try {
					Toast.loading({
						message: '处理中...',
						forbidClick: true
					})

					doSignNotice({
							noticeId: Number(this.detailId),
							replyContent: '',
							fileInfo: ''
						})
						.then(res => {

							if (res.code == 200) {
								Toast.success(res.message)
								this.$router.back()
							} else {
								Toast.error(res.message)
							}
						})


				} catch (err) {
					Toast.fail('签收失败')
				} finally {
					Toast.clear()
				}
			},

			// 撤回
			async canclePosted() {
				try {
					Toast.loading({
						message: '处理中...',
						forbidClick: true
					})

					doRecallNotice({
							id: this.detailInfo.noticeInfo.id
						})
						.then(res => {

							if (res.code == 200) {
								Toast.success(res.message)
								this.loadDetailData()
							} else {
								Toast.error(res.message)
							}
						})
				} catch (err) {
					console.error('撤回失败:', err)
					Toast.fail('撤回失败')
				} finally {
					Toast.clear()
				}
			},

			// 删除
			async handDelete() {
				try {
					await Dialog.confirm({
						title: '提示',
						message: '确定要删除该条数据吗？'
					})

					Toast.loading({
						message: '处理中...',
						forbidClick: true
					})

					doRecallNotice({
							noticeId: this.detailInfo.noticeInfo.id
						})
						.then(res => {

							if (res.code == 200) {
								Toast.success(res.message)
								this.$router.back()
							} else {
								Toast.error(res.message)
							}
						})


				} catch (err) {
					if (err === 'cancel') return
					console.error('删除失败:', err)
					Toast.fail('删除失败')
				} finally {
					Toast.clear()
				}
			},

			// 重发
			handRetry() {
				this.$router.push({
					path: '/annunciate/add',
					query: {
						id: this.detailInfo.noticeInfo.id
					}
				})
			},

			// 审批处理
			async handConsent(result) {
				if (!this.result.trim() && result === '3') {
					Toast('请填写驳回原因')
					return
				}

				try {
					this.loading = true
					Toast.loading({
						message: '处理中...',
						forbidClick: true
					})

					doHandle({
							taskId: this.taskId,
							comment: this.result,
							result: Number(result),
							linkInfo: this.approver[0] ? [{
								type: 'user',
								userId: this.approver[0].id
							}] : []
						})
						.then(res => {

							if (res.code == 200) {
								Toast.success(res.message)
								this.$router.back()
							} else {
								Toast.error(res.message)
							}
						})


				} catch (err) {
					console.error('审批失败:', err)
					Toast.fail('审批失败')
				} finally {
					this.loading = false
					Toast.clear()
				}
			},

			// 查看已读/未读记录
			goReadLog(type) {
				const {
					isNeedSign,
					yesSignList,
					noSignList,
					yesReadList,
					noReadList
				} = this.detailInfo

				this.$router.push({
					path: '/annunciate/read-log',
					query: {
						isNeedSign,
						yesList: isNeedSign == 1 ? yesSignList : yesReadList,
						noList: isNeedSign == 1 ? noSignList : noReadList,
						tabVal: type
					}
				})
			},

			// 选择审批人
			handleApproverClick(data) {
				this.approver = data.list
			},

			// 打开文件
			openFile(url) {
				window.open(url)
			},

			// 获取文件图标
			getPath(file) {
				var fileType = file.fileType
				if (fileType == '.jpg' || fileType == '.jpeg' || fileType == '.png') {
					return file.accessPath
				} else {
					var icon;
					if (fileType == '.ppt') {
						icon = '/assets/images/ic_office_ppt.png'
					} else if (fileType == '.doc' || fileType == '.docx') {
						icon = '/assets/images/ic_office_word.png'
					} else if (fileType == '.xlsx') {
						icon = '/assets/images/ic_office_excel.png'
					} else if (fileType == '.pdf') {
						icon = '/assets/images/ic_office_pdf.png'
					} else {
						icon = '/assets/images/ic_office_unknow.png'
					}
					return icon
				}
			},
		}
	}
</script>
<style lang="scss" scoped>
	.feed-container {
		padding: 5px 0 20px;
		background-color: #f5f5f5;
		min-height: 100vh;

		.section {
			border-radius: 5px;
			margin: 10px;
			padding: 5px 10px;
			background: white;
			color: #333;
			border: 1px solid #ddd;
			overflow: hidden;
			margin-top: 44px;

			.title {
				padding: 10px 0 15px;
				margin: 0 10px;
				border-bottom: 1px solid #ccc;
				font-size: 18px;
				font-weight: bold;
			}

			.html {
				padding: 10px;
			}

			.info-item {
				margin: 0 10px;
				height: 44px;
				line-height: 44px;
				display: flex;
				justify-content: space-between;
				border-bottom: 1px solid #ccc;

				&:last-child {
					border-bottom: none;
				}
			}
		}

		.section-title {
			padding-left: 10px;
			height: 36px;
			line-height: 36px;
			font-size: 16px;
			font-weight: bold;
			color: #333;
			margin: 0 0 10px;

			.title-bar {
				display: inline-block;
				vertical-align: middle;
				width: 4px;
				height: 19px;
				background: #3669f8;
				border-radius: 1px;
				margin-right: 8px;
			}
		}

		// ... 其他样式
	}
</style>